package com.lingshi.shopping_order_customer_api.controller;

import cn.hutool.json.JSONUtil;
import com.lingshi.shopping.entity.Orders;
import com.lingshi.shopping.result.BaseResult;
import com.lingshi.shopping.service.OrdersService;
import com.lingshi.shopping.service.ZfbPayService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付管理
 */
@Slf4j
@RestController
@RequestMapping("/user/payment")
public class PaymentController {

    @DubboReference
    private OrdersService ordersService;

    @DubboReference
    private ZfbPayService zfbPayService;

    /**
     * 获取支付二维码
     * @param orderId
     * @return
     */
    @PostMapping("/pcPay")
    public BaseResult pcPay(String orderId) {
        //获取订单
        Orders orders = ordersService.findById(orderId);
        //获取支付码
        String qrCodeUrl = zfbPayService.pcPay(orders);

        return BaseResult.success(qrCodeUrl);
    }

    /**
     * 支付回调
     * @param request 请求对象
     */
    @RequestMapping("/success/notify")
    public void successNotify(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        request.getParameterMap().forEach((key, value) -> {
            params.put(key,value[0]);
        });
        System.out.println("request = " + params);
        System.out.println(JSONUtil.toJsonPrettyStr(params));
//        Map<String, String[]> parameterMap = request.getParameterMap();
        System.out.println(params.getClass().getName());
        System.out.println(JSONUtil.toJsonStr(params));
        //验签
        boolean result = zfbPayService.checkSign(params);
        if (result) {
            zfbPayService.updateOrderStatus(params);
        }

    }
}
